import logging
import smtplib
from email.mime.text import MIMEText

import formencode
from pylons import config
from pylons import request, response, session, url, tmpl_context as c
from pylons.decorators import validate
from pylons.controllers.util import abort, redirect_to

from sc.lib.base import BaseController, render

log = logging.getLogger(__name__)

class ContactForm(formencode.Schema):
    subject = formencode.validators.UnicodeString(min=1)
    email = formencode.validators.Email()
    message = formencode.validators.UnicodeString(min=10)

class MainController(BaseController):
    def __before__(self):
        c.current_url = url.current()

    def index(self):
        return render('/main/index.mako')

    def uploader_info(self):
        return render('/main/uploader_info.mako')

    def contact(self):
        return render('/main/contact.mako')

    def _send_msg(self, from_address, to_address, subject, message):
        msg = MIMEText(message.encode('utf-8'))
        msg['subject'] = subject
        msg['from'] = from_address
        msg['to'] = to_address

        s= smtplib.SMTP(host=config['contact_smtp_server'])
        s.starttls()
        s.login(config['contact_smtp_username'], config['contact_smtp_password'])
        s.sendmail(msg['from'], [msg['to']], msg.as_string())
        s.close()

    @validate(schema=ContactForm, form='contact')
    def contact_submit(self):
        subject = self.form_result.get('subject')
        email = self.form_result.get('email') or config['contact_fallback_email_from']
        message = self.form_result.get('message')


        self._send_msg(email, config['contact_email_to'], subject, message)

        return redirect_to(controller='main', action='contact_submitted')

    def contact_submitted(self):
        return render('/main/contact_submitted.mako')
